package com.cloud.job;

import com.alibaba.fastjson.JSON;
import com.cloud.utils.HBaseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class CreateLogTableJob {
//    @Autowired
//    private CloudLogRecordService cloudLogRecordService;

    @Autowired
    private HBaseUtils hBaseUtils;

    @Scheduled(cron = "0 0 23 * * ? ")   //每天23执行
    public void execute() throws Exception {
        //避免两个pod同时执行，所以使用一个随机数阻塞线程几秒钟
        int randomNumber = (int) (90000 * Math.random()) + 10000;
        try {
            Thread.sleep(randomNumber);
        } catch (InterruptedException e) {
            log.error(JSON.toJSONString(e));
        }
        //目前取消了向数据库中插入数据
        String tableName = "cloud_log_record";
//        cloudLogRecordService.createTableIfAbsent(selectTableName(tableName));

        //hbase创建表
        List<String> list = new ArrayList<>();
        list.add("logs");
        hBaseUtils.createTableAndCoprocessor(selectTableName(tableName), list);
    }

    String selectTableName(String tableName) {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //创建下一个月的数据库
        calendar.add(Calendar.MONTH, 1);
        Date time = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String nextDate = sdf.format(time);
        return tableName + "_" + nextDate;
    }
}
